package com.fhz.app_client;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.widget.Toast;

import com.fhz.example.IMyAidlInterface;

public class MainActivity extends AppCompatActivity {


    private IMyAidlInterface iMyAidlInterface;
    //3.绑定服务回调
    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {


            //绑定服务成功后，返回服务端返回的binder，将其转成IMyAidlInterface调用add方法
             iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
            try {
                int num=iMyAidlInterface.add(4,6);//调用服务端的add方法并得到结果
                Toast.makeText(MainActivity.this, ""+num, Toast.LENGTH_SHORT).show();

                int sub = iMyAidlInterface.sub(2, 1);
                Toast.makeText(MainActivity.this, ""+sub, Toast.LENGTH_SHORT).show();

            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            //解除绑定时调用， 清空接口，防止内容溢出
            iMyAidlInterface=null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent();
        intent.setPackage("com.fhz.example");
        intent.setAction("com.feng.hehe");
        bindService(intent,connection,BIND_AUTO_CREATE);
    }
}